package com.ray.service;

import com.alibaba.fastjson.JSONObject;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.MessageTypeBean;
import com.ray.bean.UserBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.WeChatToMessageMapper;
import com.ray.pojo.CompanyWeChatUserPojo;
import com.ray.util.StringUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class WeChatToMessageService {
	
	@Autowired
	WeChatToMessageMapper weChatToMessageMapper;
	@Autowired
	WeiXinService weiXinService;
	
	
	/**
	 * 获取公司所有消息类型
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<MessageTypeBean> getAllMessageType(Map<?, ?> map) {
		int count=0;
		DatatablesViewPageBean<MessageTypeBean> dtcpb=new DatatablesViewPageBean<MessageTypeBean>();
		count=weChatToMessageMapper.getAllMessageTypeCount(map);
		dtcpb.setReturnData(weChatToMessageMapper.getAllMessageType(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}


	/**
	 * 获取所有消息类型
	 * @return
	 */
	public List<MessageTypeBean> getAllType() {
		return weChatToMessageMapper.getAllType();
	}

    
	/**
	 * 添加消息类型
	 * @param type(消息类型)
	 * @param deptId(部门id)
	 * @param workShopId(车间id)
	 * @return
	 * @throws ServiceException
	 */
	public void addMessageType(Map<String, String> map) {
		Assert.notNull(map.get("type"),"未获取到类型");
		Assert.notNull(map.get("deptId"),"未获取到部门");
		Assert.notNull(map.get("workShopId"),"未获取到车间");
		Assert.isTrue(checkType(map),"该消息类型已存在");
		map.put("id", StringUtil.getUUID());
		weChatToMessageMapper.addMessageType(map);
	}


	/**
	 * 校验类型是否存在
	 * @param map
	 * @return
	 */
	private boolean checkType(Map<String, String> map) {
		boolean bool=false;
		List<String> xx=weChatToMessageMapper.checkType(map);
		if(xx==null || xx.size()<=0) 
			bool=true;
		return bool;
	}

	
	
	
	

	/**
	 * 获取消息类型接收人
	 * @param id(类型id)
	 * @return
	 * @throws ServiceException
	 */
	public DatatablesViewPageBean<UserBean> getTypeUser(Map<?, ?> map) {
		Assert.notNull(map.get("id"),"未获取到类型id");
		int count=0;
		DatatablesViewPageBean<UserBean> dtcpb=new DatatablesViewPageBean<UserBean>();
		count=weChatToMessageMapper.getTypeUserCount(map);
		dtcpb.setReturnData(weChatToMessageMapper.getTypeUserData(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}


	/* 获取消息中没有的接收人
	 * @param id(类型id)
	 * @param serachWhere(搜索条件)
	 * @return
	 * @throws ServiceException
	 */
	public DatatablesViewPageBean<UserBean> getTypeNoHaveUser(Map<?, ?> map) {
		Assert.notNull(map.get("id"),"未获取到类型id");
		int count=0;
		DatatablesViewPageBean<UserBean> dtcpb=new DatatablesViewPageBean<UserBean>();
		count=weChatToMessageMapper.getTypeNoHaveUserCount(map);
		dtcpb.setReturnData(weChatToMessageMapper.getTypeNoHaveUser(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}


	/**
	 * 添加消息类型
	 * @param id(消息类型id)
	 * @param userIdArray(用户id集合)
	 * @return
	 * @throws ServiceException
	 */
	public void addTypeUser(Map map) {
		 Assert.notNull(map.get("id"), "未获取到消息id");
		 Assert.notNull(map.get("userIdArray"), "未获取到用户id");
		 String userIdArray=map.get("userIdArray").toString();
		 JSONArray jsonArray = JSONArray.fromObject(userIdArray);
		 List<String> userIdList=jsonArray.subList(0, jsonArray.size());
		 Assert.isTrue(userIdList != null && userIdList.size()>0, "请选择要添加人员");
		 map.put("userIdList", userIdList);
		 weChatToMessageMapper.addTypeUser(map);
	}


	/**
	 * 删除消息类型
	 * @param id(消息类型id)
	 * @return
	 * @throws ServiceException
	 */
	public void deleteType(Map<?, ?> map) {
		 Assert.notNull(map.get("id"), "未获取到消息id");
		 weChatToMessageMapper.deleteType(map);
	}

	/**
	 * 移除单个消息用户
	 * @param id(消息类型id)
	 * @return
	 * @throws ServiceException
	 */
	public void removeTypeUser(Map<?, ?> map) {
		Assert.notNull(map.get("id"), "未获取到消息id");
		Assert.notNull(map.get("userId"), "未获取到用户id");
		weChatToMessageMapper.removeTypeUser(map);
	}
	
	
	/**
	 * @param type(权限变更类型)
	 * @param thing(变更事项)
	 * @param remark(备注)
	 * @param openId(微信id)
	 * @return
	 */
	public boolean sendPermissionMessage(String type,String thing,String remark,String openId) {
		String accessToken=weiXinService.getAccessToken(null);
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		JSONObject data=WeixinTemplateList.packJsonPermissionChange("您收到一条权限变更提醒", "", thing, simpleDateFormat.format(new Date()), remark, null, null, null, null, null);
		String result=WeixinTemplateSender.sendWechatmsgToUser(openId, WeiXinParamesUtil.permissionChangeTemplateID, null, data, accessToken);
	    if("success".equals(result)) {
	    	return true;
	    }else {
	    	return false;
	    }
	}
	
	
   /**
    * 通过传参获取消息类型接受消息的用户
    * @param loginCompany(公司)
    * @param deptId(部门id 不分部门为null)
    * @param workShopId(车间id 不分车间为null)
    * @param type(类型)
    * @return 用户id集合
    */
   public List<String> getWeChatNewsUserIdListByParam(String loginCompany,String deptId,String workShopId ,String type){
       Map<String, String> map = new HashMap<String, String>();
	   map.put("loginCompany", loginCompany);
	   map.put("deptId", deptId);
	   map.put("workShopId", workShopId);
	   map.put("type", type);
	   return this.getWeChatNewsUserIdListByMap(map);
   }

   /**
    * 通过传map获取消息类型接受消息的用户
    * @param loginCompany(公司)
    * @param deptId(部门id 不分部门为null，可不设key)
    * @param workShopId(车间id 不分车间为null，可不设key)
    * @param type(类型)
    * @return 用户id集合
    */
  public  List<String> getWeChatNewsUserIdListByMap(Map map) {
	  Assert.notNull(map.get("type"),"未获取到类型");
	  List<String> typeIdList=weChatToMessageMapper.checkType(map);
	  if(typeIdList !=null && typeIdList.size()>0) {
		  typeIdList=weChatToMessageMapper.getUserIdListByTypeList(typeIdList);
	  }
	  return typeIdList;
  }

    /**
     * @Author: 李宇航
     * @Description: 将查出的用户的openID分别按照公司，部门id，车间id进行分组
     * @Param: int type 微信消息类型
     * @return: Map<String   ,   Map   <   String   ,   Map   <   String   ,   List   <   String>>>> groupResult
     * 分组之后的结果集键依次为公司名称，部门id，车间id，最终访问到用户openid数组
     * @Date: 2018/11/1
     */
    public Map<String, Map<String, Map<String, List<String>>>> getCompanyWeChatUsersByType(int type) {
        Map<String, Map<String, Map<String, List<String>>>> groupResult = new HashMap<>();
        List<CompanyWeChatUserPojo> companyWeChatUsers = weChatToMessageMapper.getCompanyWeChatUsersByType(type);
        for (CompanyWeChatUserPojo companyWeChatUserPojo : companyWeChatUsers) {
            String company = companyWeChatUserPojo.getCompany();
            String deptId = companyWeChatUserPojo.getDeptId();
            String workShopId = companyWeChatUserPojo.getWorkShopId();
            String openid = companyWeChatUserPojo.getOpenid();
            groupResult.computeIfAbsent(company, k -> new HashMap<>());
            groupResult.get(company).computeIfAbsent(deptId, k -> new HashMap<>());
            groupResult.get(company).get(deptId).computeIfAbsent(workShopId, k -> new ArrayList<>());
            groupResult.get(company).get(deptId).get(workShopId).add(openid);
        }
        return groupResult;
    }
	

	
//	/**
//	 * 添加微信消息接收人员
//	* @date 2018年5月12日 上午10:09:56 
//	* @author 李斌
//	* @return void 
//	* @throws
//	 */
//	public void addWeChatUser(Map<String, Object> map) throws ServiceException {
//		if(map.get("userId")==null) {
//			throw new ServiceException("用户Id为空");
//		};
//		WeChatToMessageBean weChatToMessageBean = weChatToMessageMapper.getWeChatUserByUserId(map);
//		if(weChatToMessageBean!=null) {
//			throw new ServiceException("该人员已存在,请勿重复添加");
//		}
////		List<WeiXinPeopleBean> weiXinPeopleBeans = weiXinPeopleMapper.getWexinPeopleByUserId(map);
////		if(weiXinPeopleBeans==null||weiXinPeopleBeans.size()<1) {
////			throw new ServiceException("请先关注微信公众号");
////		} 
//		weChatToMessageMapper.addWeChatUser(map);
//	}
//	
//	/**
//	 * 获取微信消息接收人员通过UserId
//	* @date 2018年5月12日 上午10:10:09 
//	* @author 李斌
//	* @return WeChatToMessageBean 
//	* @throws
//	 */
//	
//	public WeChatToMessageBean getWeChatUserByUserId(Map<String, Object> map){
//		return weChatToMessageMapper.getWeChatUserByUserId(map); 
//	}
//	 
//	/**
//	 * 获取所有微信信息接收人员
//	* @date 2018年5月12日 上午10:10:30 
//	* @author 李斌
//	* @return List<WeChatToMessageBean> 
//	* @throws
//	 */
//	public List<WeChatToMessageBean> getAllWeChatUser(Map<String, Object> map) {
//		return weChatToMessageMapper.getAllWeChatUser(map);
//	}
//	
//	/**
//	 * 更新微信消息接收人员状态
//	* @date 2018年5月12日 下午1:41:24 
//	* @author 李斌
//	* @return void 
//	* @throws
//	 */
//	public void updateWeChatUserOnStatus(Map<String, Object> map) {
//		weChatToMessageMapper.updateWeChatUserOnStatus(map);
//	}
//	
//	/**
//	 * 发送消息
//	* @date 2018年5月12日 下午4:07:13 
//	* @author 李斌
//	* @return void 
//	* @throws
//	 */
//	public void sendMessage(HttpServletRequest request,List<String> userList,String message) throws ServiceException {
//		String accessToken = weiXinService.getAccessToken(request);
//		if(accessToken.isEmpty()) {
//			throw new ServiceException("未获取到ACCESS_TOKEN!");
//		}
//		String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
//	
//	
//	}
//	
	
	
}
